package com.xmim.fulcrum.handler;

import com.xmim.core.entity.Message;
import com.xmim.core.session.user.UserSession;
import com.xmim.core.session.user.UserSessionManager;
import com.xmim.fulcrum.*;
import com.xmim.fulcrum.session.FulcrumSessionManager;
import com.xmim.fulcrum.session.UserSessionsDao;

public abstract class AbstractMessageHandler<M> implements IMessageHandler<M> {
    protected final FulcrumDiscover fulcrumDiscover;
    protected final FulcrumCodec codec;
    protected final FulcrumSessionManager senderManager;
    protected final UserSessionManager sessionManger;
    protected final UserSessionsDao userSessionsDao;
    protected final FulcrumFactory fulcrumFactory;


    public AbstractMessageHandler(FulcrumDiscover fulcrumDiscover) {
        this.fulcrumDiscover = fulcrumDiscover;
        this.fulcrumFactory = fulcrumDiscover.getFactory();
        this.codec = fulcrumFactory.getCodec();
        this.senderManager = fulcrumDiscover.getSessionManager();
        this.sessionManger = fulcrumFactory.getSessionManager();
        this.userSessionsDao = fulcrumFactory.getUserSessionsDao();
    }

    @Override
    public void handler(UserSession session, Message<M> msg) {
        M body = msg.getBody();
        Class<?> messageClass = this.getMessageClass();
        if (!this.getType().equals(msg.getType())) {
            return;
        } else if (body != null) {
            if (messageClass.equals(body.getClass())) {
                handler0(session, msg);
            } else {
                return;
            }
        } else {
            handler0(session, msg);
        }
    }

    protected abstract void handler0(UserSession session, Message<M> msg);

    protected abstract Class<?> getMessageClass();
}
